package com.liuyucheng.idea_springboot.secret.aes;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESExample {
    public static void main(String[] args) throws Exception {
        // 生成一个随机的AES密钥
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // AES-128, 也可以使用192或256位
        SecretKey secretKey = keyGen.generateKey();

        // 初始化向量（IV），AES的CBC模式需要IV
        byte[] iv = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        // 待加密的明文
        String plaintext = "Hello, this is a test message.";

        // 加密
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        byte[] encryptedData = cipher.doFinal(plaintext.getBytes("UTF-8"));

        // 将加密后的数据编码为Base64字符串
        String encodedData = Base64.getEncoder().encodeToString(encryptedData);
        System.out.println("Encrypted data (Base64): " + encodedData);

        // 解密
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] decodedData = Base64.getDecoder().decode(encodedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        String decryptedText = new String(decryptedData, "UTF-8");
        System.out.println("Decrypted data: " + decryptedText);
    }
}
